<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="form.username" @clear="getList('1')">
            <el-button slot="append" icon="el-icon-search" @click="getList('1')"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addOne()">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeStatus(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="editOne(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="removeOne(scope.row)"> </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
              <el-button type="warning" size="mini" icon="el-icon-set-up" @click.native="setRole(scope.row)"> </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 修改用户弹窗 -->
    <el-dialog :title="type == 'add' ? '添加用户' : '修改用户'" :visible.sync="dialogEditVisible">
      <el-form :model="addForm" ref="addForm" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-form-item label="用户名" prop="username" placeholder="请输入用户名">
          <el-input :disabled="type == 'edit'" v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="type == 'add'" prop="password" placeholder="请输入密码">
          <el-input type="password" :readonly="type == 'edit'" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" placeholder="请输入邮箱">
          <el-input type="email" v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" placeholder="请输入手机号">
          <el-input type="number" v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('addForm')">确定</el-button>
          <el-button @click="dialogEditVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配权限" :visible.sync="dialogSetRoleVisible" @close="setRoleDialog()">
      <div>
        <p><span>当前用户：</span>{{ userInfo.username }}</p>
        <p><span>当前角色：</span>{{ userInfo.role_name }}</p>
        <p>
          <span>选择角色：</span>
          <el-select v-model="selectedRoleId" placeholder="请选择角色" clearable filterable>
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="setRoleSubmit">确定</el-button>
        <el-button @click="dialogSetRoleVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: ''
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      //分配角色
      dialogSetRoleVisible: false,
      roleList: [], //角色列表
      userInfo: {}, //需要分配的用户
      selectedRoleId: '', //选择角色id
      //修改用户
      dialogEditVisible: false,
      addForm: {
        //新增数据
        email: '',
        mobile: ''
      },
      type: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList (type) {
      if (type == '1') {
        this.pageNum = 1
        this.pageSize = 10
      }
      const data = {
        query: this.form.username,
        pagenum: this.pageNum,
        pagesize: this.pageSize
      }
      this.$http
        .get('/users', { params: data })
        .then(res => {
          res = res.data
          // console.log(res)
          if (res.meta.status == 200) {
            this.tableData = res.data.users
            this.total = res.data.total
            //  console.log('userList',this.userList)
          } else {
            this.$message({ type: 'error', message: res.meta.msg })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getRoleList () {
      //获取角色列表
      this.$http
        .get('/roles')
        .then(res => {
          res = res.data
          console.log(res)
          if (res.meta.status == 200) {
            this.roleList = res.data
            console.log('roleList', this.roleList)
          } else {
            this.$message({ type: 'error', message: res.meta.msg })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    setRoleDialog () {
      //关闭弹窗时
      this.selectedRoleId = ''
      this.dialogSetRoleVisible = false
    },
    setRole (row) {
      //分配角色显示
      this.userInfo = JSON.parse(JSON.stringify(row))
      this.getRoleList()
      this.dialogSetRoleVisible = true
    },
    setRoleSubmit () {
      //分配角色提交
      if (!this.selectedRoleId) {
        this.$message({ type: 'error', message: '请选择分配角色' })
        return false
      }
      const data = {
        id: this.userInfo.id,
        rid: this.selectedRoleId
      }
      console.log('data', data)
      this.$confirm(`确定提交?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .put(`/users/${this.userInfo.id}/role`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.$message({ type: 'success', message: res.meta.msg })
              this.dialogSetRoleVisible = false
              this.getList('1')
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    changeStatus (row) {
      //修改用户状态
      // console.log('mg_state',row.mg_state)
      const data = {
        id: row.id,
        type: row.mg_state
      }
      this.$http
        .put(`/users/${row.id}/state/${row.mg_state}`, data)
        .then(res => {
          res = res.data
          // console.log(res)
          if (res.meta.status == 200) {
            this.$message({ type: 'success', message: '修改成功!' })
            this.getList('1')
          } else {
            row.mg_state = !row.mg_state
            this.$message({ type: 'error', message: res.meta.msg })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    addOne () {
      //新增显示
      this.type = 'add'
      this.addForm = {}
      this.dialogEditVisible = true
    },
    editOne (row) {
      //修改显示
      this.type = 'edit'
      this.dialogEditVisible = true
      this.addForm = JSON.parse(JSON.stringify(row))
    },
    onSubmit (formName) {
      //确定
      // console.log('addForm',this.addForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.type == 'add') {
            this.addSubmit()
          } else {
            this.editSubmit()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addSubmit () {
      //新增用户提交数据
      const data = {
        username: this.addForm.username,
        password: this.addForm.password,
        email: this.addForm.email,
        mobile: this.addForm.mobile
      }
      console.log('data', data)
      this.$confirm(`确定提交?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/users`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 201) {
              this.dialogEditVisible = false
              this.$message({ type: 'success', message: res.meta.msg })
              this.getList('1')
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    editSubmit () {
      //修改用户提交数据
      const data = {
        id: this.addForm.id,
        email: this.addForm.email,
        mobile: this.addForm.mobile
      }
      console.log('data', data)
      this.$confirm(`确定修改用户${this.addForm.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .put(`/users/${this.addForm.id}`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.dialogEditVisible = false
              this.$message({ type: 'success', message: '修改成功!' })
              this.getList('1')
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    removeOne (row) {
      //删除用户
      const data = {
        id: row.id
      }
      console.log('data', data)
      this.$confirm(`确定删除用户${row.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .delete(`/users/${row.id}`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.getList('1')
              this.$message({ type: 'success', message: '删除成功!' })
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.pageNum = val
      this.getList()
    }
  }
}
</script>

<style scoped></style>
